import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {User} from "./user";
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../util/response-util";
import {UsersService} from "./users.service";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {API, MsgConstants} from "../../../constants/constants";
import {MsgResult} from "../../../models/msg-result";
import {TableUtil} from "../../../util/table-util";

declare var $;

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html'
})
export class UsersComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  users: User[];

  userCode: Array<string> = [];

  arrayId: Array<string> = [];

  table

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private pageSubject : PageSubject,
    private tableUtil : TableUtil,
    private responseUtil : ResponseUtil,
    private dialogService : OneDialogService,
    private usersService : UsersService
  ) { }

  proxy = {
    "userAdd": () => this.userAdd(),
    "userDelete": () => this.userDelete(),
    "userUpdate": () => this.userUpdate(),
    "userAllotAccount": () => this.userAllotAccount(),
    "userBatchAllotAccount": () => this.userBatchAllotAccount()
  }

  /**
   * 初始化完组件视图及其子视图之后调用
   */
  ngAfterViewInit() {
    this.operation.proxy = this.proxy
  }

  ngOnInit() {
    this.pushPage();
    this.loadUsers();
  }


  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("用户系统", "");
    this.pageSubject.pushPage("用户管理", "查询");
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 添加按钮事件
   * 1.点击跳转到添加用户界面
   */
  userAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   *  弹出删除弹窗
   *  1.判断是否选择数据；
   *  2.弹出确定删除弹窗；
   */
  userDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    this.arrayId=this.tableUtil.getCloumns(rows,"userId");
    //用于修改账户的状态
    this.userCode=this.tableUtil.getCloumns(rows,"userCode");
    if (this.arrayId.length == 0) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    if (this.arrayId.length != 0 ) {
      this.usersService.deleteUsers(this.arrayId,this.userCode).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 修改操作
   * 1.判断是否选择数据；
   * 2.跳转到修改页面；
   */
  userUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    this.arrayId=this.tableUtil.getCloumns(rows,"userId");
    if (this.arrayId.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update', {userId: this.arrayId[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 分配账户
   * 1.判断是否选择数据；
   * 2.跳转到分配账户页面；
   */
  userAllotAccount() {
    let rows = this.table.bootstrapTable('getSelections');
    this.arrayId = this.tableUtil.getCloumns(rows, "userId");
    if (this.arrayId.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      let userCode = this.tableUtil.getCloumn(rows[0], "userCode");
      if (!!userCode) {
        this.dialogService.modalInfoWithCancelBtn("该用户已分配账户! 是否确定重新分配？", () => this.userAssignAccountRoute(), () => this.search());
      } else {
        this.userAssignAccountRoute();
      }
    }
  }

  /**
   * 分配账户路由
   */
  private userAssignAccountRoute(){
    this.router.navigate(['speedy', {userId: this.arrayId[0]}], {relativeTo: this.route});
  }

  /**
   * 批量分配账户
   * 1.暂未实现
   */
  userBatchAllotAccount() {
    if (this.arrayId.length > 1) {
      this.router.navigate(['accs', {userArrId: this.arrayId[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 用户查询
   */
  loadUsers() {
    this.table = this.tableUtil.load("one_table_user",{
      columns: [
        {checkbox: true },
        {field: "userId", title: 'ID', align: 'left', visible: false ,switchable:false},
        {field: "name", title: '名称', align: 'left'},
        {field: "userCode", title: '用户编号', align: 'left'},
        {field: "type", title: '用户类型', align: 'left', formatter: this.yesOrNoFormat},
        {field: "regionName", title: '行政名称', align: 'left'},
        {field: "duty", title: '职位', align: 'left'},
        {field: "phone", title: '联系方式', align: 'right'},
        { field: "creatorName",title:'创建人',align:'left' ,visible: false },
        { field: "CREATE_DATE" ,title:'创建日期',align:'left',sortName:'CREATE_DATE',sortable:true ,visible: false },
        { field: "editorName" ,title:'修改人',align:'left', visible: false},
        { field: "MODIFIED_DATE" ,title:'修改日期',align:'left',visible: false ,sortName:'MODIFIED_DATE',sortable:true},
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      // singleSelect: true,//单选
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_users",
      url: API.userPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#userName").val();
        params.userCode = $("#userCode").val();
        params.regionName = $("#regionName").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result,(result)=>{

          result.data.rows.forEach(function (value) {
            value.CREATE_DATE = value.createDate || '';
            value.MODIFIED_DATE = value.modifiedDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'MODIFIED_DATE',  //默认
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      //css
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '0') {
      return "管理员";
    }
    if (value == '1') {
      return "企业用户"
    }
    if (value == '2') {
      return "政府用户"
    }
    if (value == '3') {
      return "运维"
    }
    if (value == '4') {
      return "演示"
    }
    if (value == '5') {
      return "第三方"
    }
    if (value == '5') {
      return "公众"
    }
  }

}
